/* *
@Author: MaLiang
@Date: 2023-06-08
@LastEditors: --
@LastEditTime: --
@path: src/hooks/use-scroll-record.ts
@Description: keepalive页面自定义滚动区域记录滚动位置
* */
import { nextTick, onActivated, onDeactivated, Ref } from 'vue'
import { useRoute } from 'vue-router'
function useScrollRecord(scrollNode: Ref) {
  const $route = useRoute()
  const pageName = $route.name
  const cacheScrollName = 'qmp-cache-scroll-name'
  let scrollTop = 0

  onActivated(() => {
    nextTick(() => {
      if (scrollNode.value) {
        scrollNode.value.addEventListener('scroll', (val: any) => {
          scrollTop = val.target.scrollTop
        })
      }
    })

    if (pageName && scrollNode.value) {
      const scrollRecord = sessionStorage.getItem(cacheScrollName)
      if (scrollRecord) {
        let scrollRecordMap: {
          [key: string]: any
        } = {}
        scrollRecordMap = JSON.parse(scrollRecord)
        scrollNode.value.scrollTop = scrollRecordMap[pageName as string] || 0
      }
    }
  })
  onDeactivated(() => {
    nextTick(() => {
      if (scrollNode.value) {
        scrollNode.value.removeEventListener('scroll', () => {})
      }
    })

    if (pageName && scrollNode.value) {
      let scrollRecord = sessionStorage.getItem(cacheScrollName)
      //   const scrollTop = scrollNode?.value?.scrollTop
      let scrollRecordMap: {
        [key: string]: any
      } = {}
      if (scrollRecord) {
        scrollRecordMap = JSON.parse(scrollRecord)
        scrollRecordMap[pageName as string] = scrollTop
        sessionStorage.setItem(cacheScrollName, JSON.stringify(scrollRecordMap))
      } else {
        sessionStorage.setItem(
          cacheScrollName,
          JSON.stringify({
            [pageName]: scrollTop
          })
        )
      }
    }
  })
}

export default useScrollRecord
